<?PHP
/*
+--------------------------------------------------------------------------
|   Social Media v2.0.0
|   ========================================
|   by Nathan Harber
|   http://www.mediascripts.com
|   ========================================
|   File: SM.Class.php
+--------------------------------------------------------------------------
*/

define('NEXT_PAGE', 6);

class smclass {

  var $smarty;
  var $db;
  var $user;
  var $InputFilter;
  
  var $config 	= array();
  var $lang 	= array();
  var $input	= array();
  
  var $tpl_out = array();
  var $tpl_page_cache = array();
  var $tpl_page_lock = false;
  
  //=====================================================
  //  Load Language                 
  //=====================================================
  function load_language($lang_file = "")
  {      	  	  
	  if ( isset($this->input['slang']) )
	  {
		  $lid = $this->quote_smart( $this->input['slang'] );
	  }
	  elseif ( isset($_COOKIE['sm_lang']) )
	  {
		  $lid = $this->quote_smart( $_COOKIE['sm_lang'] );
	  }
	  else
	  {
	      $lid = $this->user->check_login() ? $this->user->settings['language'] : $this->config['default_lang'];
	  }
	  
	  $linfo = $this->db->quick_fetch("SELECT ldir FROM languages WHERE lid = '".$lid."'");
	  $lang_id = $linfo['ldir'];
	  
	  if ( $lang_id == "" )
	  {
	      $lang_id = "en";
	  }
	  
      require_once($this->config['sitepath']."/lang/".$lang_id."/".$lang_file.".php");
	  
	  if ( isset($language) AND is_array( $language ) )
      {
          foreach ($language as $k => $v)
          {
              $this->lang[$k] = $v;
			  $this->lang[$k] = str_replace('[sitename]', 	$this->config['sitename'], 	$this->lang[$k]);
              $this->lang[$k] = str_replace('[siteurl]', 	$this->config['siteurl'], 	$this->lang[$k]);
              $this->lang[$k] = str_replace('[sitepath]', 	$this->config['sitepath'], 	$this->lang[$k]);
          }
		  
          $this->tpl('lang', $this->lang);
      }
      
      return $this->lang;
  }  
  
  //=====================================================
  //  Set Cookie     
  //=====================================================
  function set_cookie( $name, $value="", $sticky=1, $expires_days=0 )
  {
      if ( $sticky == 1 )
      {
          $expires = time() + ( 60*60*24*365 );
      }
	  else if ( $expires_days )
	  {
	      $expires = time() + ( $expires_x_days * 86400 );
	  }
	  else
	  {
	      $expires = FALSE;
	  }
	  
	  $cookie_domain = ( $this->config['cookie_domain'] == "" ? "" : $this->config['cookie_domain'] );
	  $cookie_path = ( $this->config['cookie_path'] == "" ? "/" : $this->config['cookie_path'] );
	  
	  @setcookie( $name, $value, $expires, $cookie_path, $cookie_domain);
  }
  
  //=====================================================
  //  Assign Template Variable     
  //=====================================================
  function tpl($key, $value)
  {  
      $this->smarty->assign($key, $value);
  }
  
  //=====================================================
  //  Assign Template Variable (Array)          
  //=====================================================
  function tpl_array($input)
  {  
	  foreach ($input as $key => $value)
      {
          $this->tpl($key, $value);
      }
  }
  
  //=====================================================
  //  Set Page Title             
  //=====================================================
  function set_title($title)
  { 
      $this->tpl("page_title", $title);
  }
  
  //=====================================================
  //  Set Meta Keywords           
  //=====================================================
  function set_meta_keywords($keywords)
  { 
      $this->tpl("meta_keywords", $keywords);
  }
  
  //=====================================================
  //  Set Meta Description          
  //=====================================================
  function set_meta_desc($desc)
  { 
      $this->tpl("meta_desc", $desc);
  }
  
  //=====================================================
  //  Set Page Tab           
  //=====================================================
  function set_tab($tab)
  { 
      $this->tpl("page_tab", $tab);
  }
  
  //=====================================================
  //  Set Page Menu          
  //=====================================================
  function set_menu($menu)
  { 
      $this->tpl("page_menu", $menu);
  }
  
  //=====================================================
  //  Add To Template Display Cache            
  //=====================================================
  function add_page_cache($page, $key = "")
  { 	  
	  if ( !$this->tpl_page_lock )
	  {
	      $new_key = ($key ? $key : count($this->tpl_page_cache) + 1);
		  $this->tpl_page_cache[$new_key] = $page;
	  }
  }
  
  //=====================================================
  //  Remove From Template Display Cache            
  //=====================================================
  function remove_page_cache($page)
  { 
  	  unset($this->tpl_page_cache[array_search($page, $this->tpl_page_cache)]);
  }
  
  //=====================================================
  //  Lock Page Cache        
  //=====================================================
  function lock_page_cache()
  {
      $this->tpl_page_lock = true;
  }
  
  //=====================================================
  //  Un-Lock Page Cache        
  //=====================================================
  function unlock_page_cache()
  {
      $this->tpl_page_lock = false;
  }
  
  //=====================================================
  //  Output Template Display Cache            
  //=====================================================
  function output_page_cache()
  { 
      ksort($this->tpl_page_cache);
	  
	  foreach ( $this->tpl_page_cache as $p )
	  {
	      $this->display_tpl($p);
	  }
  }  
  
  //=====================================================
  //  Display Template Bit           
  //=====================================================
  function display_tpl($page)
  { 
      $this->smarty->display($this->config['temp_dir'].'/'.$page.'.tpl');
  }
  
  //=====================================================
  //  Grab Email Template      
  //=====================================================
  function fetch_email($name)
  {
      return $this->smarty->fetch($this->config['sitepath']."/common/emails/".$name);
  }
  
  //=====================================================
  //  Paging      
  //=====================================================
  function pagination($page_current, $page_total, &$page_from, &$page_to, &$page_previous, &$page_next, $total_items = "")
  {	  
	  $page_from 		= ($page_current - NEXT_PAGE > 0 ? $page_current - NEXT_PAGE : 1);
      $page_to 			= ($page_current + NEXT_PAGE <= $page_total ? $page_current + NEXT_PAGE : $page_total);
      $page_previous	= ($page_current <= 1 ? '' : $page_current - 1);
      $page_next 		= ($page_current >= $page_total ? '' : $page_current + 1);
	  
	  $out = array( 'page_current' 	=> $page_current, 
	  				'page_total' 	=> $page_total, 
					'page_from' 	=> $page_from, 
					'page_to' 		=> $page_to, 
					'page_previous' => $page_previous, 
					'page_next' 	=> $page_next, 
					'total_items' 	=> $total_items
				  );
					
	  $this->tpl_array($out);
  }
  
  //=====================================================
  //  Fetch OS
  //  Return: unknown, windows, mac            
  //=====================================================
  function fetch_os()
  {
      $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
		
	  if (strstr($useragent, 'mac'))
	  {
		  return 'mac';
	  }
		
	  if (preg_match('#wi(n|n32|ndows)#', $useragent))
	  {
		  return 'windows';
	  }
		
	  return 'unknown';
  }
  
  //=====================================================
  //  Get File Extension                
  //=====================================================
  function _get_file_extension($file)
  {
      $ext = explode(".", $file);
      $extcount = count($ext);
	  return strtolower($ext[$extcount - 1]);
  }
  
  //=====================================================
  //  Get File Size               
  //=====================================================
  function _get_file_size($filepath, $show_format=true)
  {
      $filesize = @filesize($filepath);
	  $filesize = $this->size_format($filesize, $show_format);
	  
	  return $filesize;
  }
  
  //=====================================================
  //  Size Format                
  //=====================================================
  function size_format($bytes = "", $show_format=true)
  {
      $retval = "";
      
      if ($bytes >= 1048576) 
	  {
          $retval = round($bytes / 1048576 * 100) / 100;
		  $format = 'MB';
      } 
	  elseif ($bytes >= 1024) 
	  {
          $retval = round($bytes / 1024 * 100) / 100;
		  $format = 'KB';
      } 
	  else 
	  {
          $retval = $bytes;
		  $format = 'Bytes';
      }
	  
	  $retval .= ( $show_format ? $format : '' );
      
      return $retval;
  }
  
  //=====================================================
  //  Calculate File Size In MB                
  //=====================================================
  function calc_size_mb($filepath)
  {
      $filesize = @filesize($filepath);
	  $retval = round($filesize / 1048576 * 100) / 100;
	  
	  return $retval;
  }
  
  //=====================================================
  //  Get Response String (Encoding Server)           
  //=====================================================
  function GetResponseString($url)
  {
      $xml = '';

	  if(!((int)ini_get("allow_url_fopen")))
	  { 
	      $ch = curl_init();
		  curl_setopt ($ch, CURLOPT_URL, $url);
		  curl_setopt ($ch, CURLOPT_HEADER, 0);
		  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		  $xml = curl_exec($ch);
		  curl_close ($ch);
	  }
	  else
	  {
		  $xml = file_get_contents($url);
	  }
	
      return $xml;
  }
  
  //=====================================================
  //  Redirect          
  //=====================================================
  function redirect($location)
  { 
      header('Location: '.$this->config['siteurl'].'/'.$location);
  }
  
  //=====================================================
  //  Redirect URL        
  //=====================================================
  function redirect_url($location)
  { 
      header('Location: '.$location);
  }
  
  //=====================================================
  //  Clean int Array
  //=====================================================
  function clean_int_array( $array=array() )
  {
      $return = array();
		
	  if ( is_array( $array ) and count( $array ) )
	  {
	      foreach( $array as $k => $v )
		  {
		      $return[ intval($k) ] = intval($v);
		  }
	  }
		
	  return $return;
  }
    
  //=====================================================
  //  Parse Incoming $_POST & $_GET       
  //=====================================================
  function parse_incoming()
  {    	
	  $input = $this->clean_incoming( $_GET, array() );
  	  $input = $this->clean_incoming( $_POST, $input );
	  
	  $this->input = $input;
	  unset($input);
	  
	  $this->input['request_method'] = strtolower($_SERVER['REQUEST_METHOD']);
  }
  
  //=====================================================
  //  Clean Incoming $_POST & $_GET       
  //=====================================================
  function clean_incoming(&$data, $input=array(), $num = 0)
  {
      if($num >= 10)
	  {
		  return $input;
	  }
		
	  foreach($data as $k => $v)
	  {
	      if (is_array($v))
		  {
			  $input[$k] = $this->clean_incoming($data[$k], array(), $num++);
		  }
		  else
		  {	
		      $k = $this->clean_key($k);
			  $v = $this->clean_value($v);
			  $input[$k] = $v;
		  }
	  }
		
	  return $input;
  }
  
  //=====================================================
  //  Clean $_POST & $_GET Key   
  //=====================================================
  function clean_key($key)
  {
      if ($key == "")
      {
    	  return "";
      }
    	
      $key = htmlspecialchars(urldecode($key));
      $key = preg_replace( "/\.\./"           , ""  , $key );
      $key = preg_replace( "/\_\_(.+?)\_\_/"  , ""  , $key );
      $key = preg_replace( "/^([\w\.\-\_]+)$/", "$1", $key );
    	
      return $key;
  }
  
  //=====================================================
  //  Clean $_POST & $_GET Value  
  //=====================================================
  /*function clean_value($val)
  {
      if ( $val == "" )
      {
          return "";
      }
    
      $val = $this->removeslashes($val);
    	
      $val = str_replace( "&", "&amp;", $val);
      $val = str_replace( "<!--", "&#60;&#33;--", $val);
      $val = str_replace( "-->", "--&#62;", $val);
      $val = preg_replace( "/<script/i", "&#60;script", $val);
      //$val = str_replace( "\n", "<br />", $val);
      $val = str_replace( "$", "&#036;", $val);
      $val = str_replace( "\r", "", $val);
      $val = str_replace( "!", "&#33;", $val);
	  //$val = str_replace( '"', "&quot;", $val);
	  //$val = str_replace( "'", "&#39;", $val);

	  $val = preg_replace("/&amp;#([0-9]+);/s", "&#\\1;", $val);
	  $val = preg_replace("/&#(\d+?)([^\d;])/i", "&#\\1;\\2", $val);
    	
      return $val;
  }*/
  
  function clean_value($val)
  {
      if ( $val == "" )
      {
          return "";
      }
	  
	  $val = $this->removeslashes($val);
	  $val = $this->InputFilter->process($val);
	  
	  return $val;
  }
  
  //=====================================================
  //  Clean HTML                 
  //=====================================================
  function clean_html($text, $keep_html=true, $tags="")
  {
      if ( $text == "" )
      {
          return "";
      }
	  
	  $text = $this->removeslashes($text);
	  
	  $text = preg_replace( "/<script/i"    , "&#60;script"         , $text );
	  $text = preg_replace( "/<iframe/i"    , "&#60;iframe"         , $text );
	  $text = preg_replace( "/<meta/i"    	, "&#60;meta"        	, $text );
	  $text = preg_replace( "/<link/i"    	, "&#60;link"         	, $text );
	  $text = preg_replace( "/<script/i"    , "&#60;script"         , $text );
	  $text = preg_replace( "/javascript/i" , "j&#097;v&#097;script", $text );
	  $text = preg_replace( "/alert/i"      , "&#097;lert"          , $text );
	  $text = preg_replace( "/about:/i"     , "&#097;bout:"         , $text );
	  $text = preg_replace( "/onmouseover/i", "&#111;nmouseover"    , $text );
	  $text = preg_replace( "/onclick/i"    , "&#111;nclick"        , $text );
	  $text = preg_replace( "/onload/i"     , "&#111;nload"         , $text );
	  $text = preg_replace( "/onsubmit/i"   , "&#111;nsubmit"       , $text );
	  $text = preg_replace( "/<body/i"      , "&lt;body"            , $text );
	  $text = preg_replace( "/<html/i"      , "&lt;html"            , $text );
      $text = preg_replace( "/document\./i" , "&#100;ocument."      , $text );
	  
	  if ( !$keep_html )
	  {
	      $text = strip_tags($text, $tags);
	  }
	  
	  return $text;
  }
  
  //=====================================================
  //  SQL Injection Protection                 
  //=====================================================
  function quote_smart($value)
  {  
      if (!is_numeric($value))
      {
          $value = mysql_real_escape_string($value);
      }
	  
      return $value;
  }
  
  //=====================================================
  //  My NL2BR              
  //=====================================================
  function my_nl2br($t="")
  {
      return str_replace( "\n", "<br />", $t );
  }
  
  //=====================================================
  //  Remove Slashes (If magic_quotes enabled)                
  //=====================================================
  function removeslashes($t)
  {
	  if ( get_magic_quotes_gpc() )
	  {
    	  $t = stripslashes($t);
		  $t = preg_replace( "/\\\(?!&amp;#|\?#)/", "&#092;", $t );
      }
    	
      return $t;
  }
  
  //=====================================================
  //  Check Module Status
  //=====================================================
  function check_module( $mkey = "" )
  {
      if ( $mkey == "" )
	  {
	      return false;
	  }
	  
	  $mkey = $this->quote_smart($mkey);
	  $result = $this->db->quick_fetch("SELECT enabled FROM modules WHERE mkey = '".$mkey."'");
	  
	  return ($result['enabled'] == 1 ? true : false);
  }
  
  //=====================================================
  //  Set Module Disabled Page
  //=====================================================
  function module_disabled( $title, $message )
  {
      $this->tpl( "module_title", $title );
	  $this->tpl( "module_msg", $message );
  }
  
  //=====================================================
  //  Show Error Page
  //=====================================================
  function display_error_page( $title, $message )
  {
      $this->tpl( "error_title", $title );
	  $this->tpl( "error_msg", $message );
	  
	  $this->add_page_cache( "error_display" );
  }
  
  //=====================================================
  //  Log Error                
  //=====================================================
  function log_error( $e_title, $e_msg, $close_conn=false )
  {
	  // Open connection?
	  if ($close_conn) $this->db->connect();
	  
	  // Log error
	  $this->db->do_insert( "error_logs", array("error_title" => $e_title, "error_msg" => $e_msg, "error_date" => date("Y-m-d")) );
	  
	  // Close connection?
	  if ($close_conn) $this->db->close();
  } 
  
  //=====================================================
  //  Bad Words                
  //=====================================================
  function parse_badwords($text = "")
  {
      if ($text == "")
	  {
	      return "";
	  }
	  
	  if ($this->config['enable_bw_filter'] == 0)
	  {
	      return $text;
	  }
	  
	  $this->db->query("SELECT word, swop, m_exact FROM badwords");
	  $bad_words = $this->db->fetch_rows();
	  
	  if ( count($bad_words > 0) )
	  {
	      foreach($bad_words as $aid => $r)
		  {	
		      if ($r['swop'] == "")
			  {
			      $replace = '*****';
			  }
			  else
			  {
			      $replace = $r['swop'];
			  }	
					
			  $r['word'] = preg_quote($r['word'], "/");
				
			  if ($r['m_exact'] == 1)
			  {
			      $text = preg_replace( "/(^|\b)".$r['word']."(\b|!|\?|\.|,|$)/i", "$replace", $text );
			  }
			  else
			  {
			      $text = preg_replace( "/".$r['word']."/i", "$replace", $text );
			  }
		  }
	  }
	  
	  return $text;
  }
  
  //=====================================================
  //  Read Directory             
  //=====================================================
  function read_dir( $dir_path, $type = "files", $sort = true, $no = array(), $dropdown = false, $novalue = false )
  {
      $results = array();
      $handler = @opendir($dir_path);
						  
	  $no2 = array(".", "..");
	  $not_allowed = array_merge($no, $no2);
	  
	  while (false !== ($file = readdir($handler)))
	  {
	      //-----------------------------------------
		  //  Files
		  //-----------------------------------------
		  if ( $type == "files" )
		  {
		      if (!is_dir( $dir_path."/".$file ))
			  {
				  if ( !in_array($file, $not_allowed) )
				  {
					  $results[] = $file;
				  }
			  }
		  }
		  
		  //-----------------------------------------
		  //  Directories
		  //-----------------------------------------
		  elseif ( $type == "dirs" )
		  {
			  if (is_dir( $dir_path."/".$file ))
			  {
				  if ( !in_array($file, $not_allowed) )
				  {
					  $results[] = $file;
				  }
			  }
		  }
		  
		  //-----------------------------------------
		  //  Files + Directories
		  //-----------------------------------------
		  else
		  {
		      if ( !in_array($file, $not_allowed) )
			  {
			      $results[] = $file;
			  }
		  }
	  }
						  
      closedir($handler);	
	  sort($results);	
	  
	  // Dropdown Menu?
	  if ( $dropdown )
	  {
	      $drop = array();
		  
		  if ( $novalue )
		  {
		      $drop[] = array("", "None");
		  }
		  
		  foreach ($results as $r)
		  {
		      $drop[] = array($r, $r);
		  }
		  
		  return $drop;
	  }
	  
	  return $results;
  }
  
  //=====================================================
  //  Copy Directory             
  //=====================================================
  function copy_dir($from_path, $to_path, $mode = 0777)
  {
      $from_path = preg_replace( "#/$#", "", $from_path);
  	  $to_path   = preg_replace( "#/$#", "", $to_path);
	
	  if ( !is_dir($from_path) )
	  {
		  return false;
	  }
	
	  if ( !is_dir($to_path) )
	  {
	      if ( !@mkdir($to_path, $mode) )
		  {
				return false;
		  }
		  else
		  {
		      @chmod($to_path, $mode);
		  }
	  }
		
	  if (is_dir($from_path))
	  {
	      $handle = opendir($from_path);
			
		  while (($file = readdir($handle)) !== false)
		  {
		      if (($file != ".") && ($file != ".."))
			  {
			      if ( is_dir( $from_path."/".$file ) )
				  {
				      $this->copy_dir($from_path."/".$file, $to_path."/".$file);
				  }
					
				  if ( is_file( $from_path."/".$file ) )
				  {
				      copy($from_path."/".$file, $to_path."/".$file);
					  @chmod($to_path."/".$file, 0777);
				  } 
			  }
		  }
		  
		  closedir($handle); 
	  }

	  return true;
  }
  
  //=====================================================
  //  Remove Directory             
  //=====================================================
  function remove_dir($file)
  {
      $errors = 0;
		
	  $file = preg_replace( "#/$#", "", $file );
		
	  if ( file_exists($file) )
	  {			
		  @chmod($file, 0777);
		
		  if ( is_dir($file) )
		  {
		      $handle = opendir($file);
				
			  while (($filename = readdir($handle)) !== false)
			  {
			      if (($filename != ".") && ($filename != ".."))
				  {
				      $this->remove_dir($file."/".$filename);
				  }
			  }
				
			  closedir($handle);
				
			  if ( ! @rmdir($file) )
			  {
			      $errors++;
			  }
		  }
		  else
		  {
		      if ( ! @unlink($file) )
			  {
			      $errors++;
			  }
		  }
	  }
		
	  if ($errors == 0)
	  {
	      return true;
	  }
	  else
	  {
	      return false;
	  }
  }
  
}

?>